package tij4.concurrent.exercise.ex31;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Philosopher implements Runnable{
    private Chopstick left;
    private Chopstick right;
    private LinkedBlockingQueue<Chopstick> bin;
    private ChopsticksCage chopsticksCage;
    private final int id;
    private final int ponderFactor;
    private Random random = new Random(47);

    private void pause() throws InterruptedException {
        if (ponderFactor == 0){ //不要思考直接去吃,会造成争抢筷子,从而造成死锁
            return;
        }
        TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFactor * 250));
    }

    public Philosopher(Chopstick left, Chopstick right, LinkedBlockingQueue<Chopstick> linkedBlockingQueue,
                       int id, int ponderFactor) {
        this.left = left;
        this.right = right;
        this.bin = linkedBlockingQueue;
        this.id = id;
        this.ponderFactor = ponderFactor;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(this + " " + "thinking");
                pause();
                //饿了,想吃
                System.out.println(this + " " + "grabbing right");
//                right.take();
                right = bin.take();
                System.out.println(this + " grabbing left");
//                left.take();
                left = bin.take();
                System.out.println(this + " eating");
                pause();
//                right.drop();
//                left.drop();
                bin.put(right);
                bin.put(left);
            }
        }catch (InterruptedException e) {
            System.out.println(this + " exiting via interrupt");
        }
    }

    @Override
    public String toString() {
        return "Philosopher " + id;
    }
}
